package net.sf.borg.control;

import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;

import net.sf.borg.control.systemLogin.BorgNameLoginSystem;
import net.sf.borg.control.systemLogin.LoginSystem;
import net.sf.borg.model.db.jdbc.JdbcDB;
import net.sf.borg.model.db.jdbc.SystemDB;

/**
 * Class SystemManager
 *
 * Provides static functionality for requiring a user to
 * create new login ID, switch IDs, and actually login
 * to this application.
 *
 * BORG/Open Source Information here.
 *
 * Created in UF Software Engineering - Summer 2009
 * @author Matthew Carroll
 */
public class SystemManager {

	/*
	 * Restarts the system and upon restart, the login system
	 * will ask the user to create a new user ID.
	 */
	public static void doNewUser() {
		BorgNameLoginSystem.getInstance().setLoginState(LoginSystem.LoginState.NEWUSER);
		Borg b = Borg.getReference();
		b.restart();
	}
	
	/*
	 * Restarts the system and upon restart, the login system
	 * will ask the user to choose a user ID.
	 */
	public static void doSwitchUser() {
		BorgNameLoginSystem.getInstance().setLoginState(LoginSystem.LoginState.CHOOSEUSER);
		Borg b = Borg.getReference();
		b.restart();
	}
	
	/*
	 * Opens and runs the login system - the initial state of this login
	 * system may be set by doNewUser() or doSwitchUser().
	 */
	public static boolean doLogin() {
		//clear any pre-existing db connections (like if the client asked to switch users through menu options in the program)
		try {
			Connection conn = JdbcDB.getConnection();
			if(conn != null) {
				conn.close();
			}
		}catch (SQLException e) {
			
		}
		
		LoginSystem loginSystem = BorgNameLoginSystem.getInstance();
		//init SystemDB to use in login system
		final String SYSTEM_DB_PATH = "system";
		final String SYSTEM_DB_NAME = "system_";
		
		boolean success = false;
		
		JdbcDB.setDBPath(SYSTEM_DB_PATH + File.separator + SYSTEM_DB_NAME);
		String dbDir = JdbcDB.buildDbDir();
		
		//attempt to login a user
		try {
			SystemDB systemDB = new SystemDB(dbDir);
			loginSystem.setDB(systemDB);
			
			success = loginSystem.runLogin();
			systemDB.close();
		}catch( Exception e ) {
			System.out.println("Failed to create new SystemDB reference; error: " + e);
		}
		
		return success;
	}
	
}
